const router = require('koa-router')()
const {getList,getDetail,newBlog,updateBlog,delBlog}=require('../controller/blog.js')
const {SuccessModel,ErrorModel}=require('../model/resModel')
const loginCheck=require('../middleware/loginCheck')

router.prefix('/api/blog')

//获取博客列表
router.get('/list',async function (ctx, next) {
  let author=ctx.query.username || '';
  let keyword=ctx.query.keyword || '';
  const listData=await getList(author,keyword)
  ctx.body = new SuccessModel(listData)
})

//获取博客详情
router.get('/detail',async function (ctx, next) {
  let id=ctx.query.id;
  const listData=await getDetail(id);
  ctx.body = new SuccessModel(listData)
})

//新建一篇博客
router.post('/new',loginCheck,async function (ctx, next) {
  const blog=ctx.request.body;
  blog.author=ctx.session.username;
  const listData=await newBlog(blog);
  ctx.body = new SuccessModel(listData)
})

//更新一篇博客
router.post('/update',loginCheck,async function (ctx, next) {
  const id=ctx.query.id;
  const blog=ctx.request.body;
  const listData=await updateBlog(id,blog);
  // if(listData){
    ctx.body =new SuccessModel(listData)
  // }else{
  //   ctx.body= new ErrorModel('更新博客失败')
  // }
  
})

//删除一篇博客
router.post('/del',loginCheck,async function (ctx, next) {
  const id=ctx.request.body.id;
  const listData=await delBlog(id);
  // if(listData){
    ctx.body = new SuccessModel(listData);
  // }else{
  //   ctx.body= new ErrorModel('删除博客失败')
  // }
  
})
module.exports = router